<?php
include("functions_account.php");

if(checkAdminLogin()===true)
{
    include ("../includes/phpmailer/function.sendmail.php");
    include ("functions_module.php");
    include("functions_file.php");
    include("functions_html.php");    
    include("functions_photo.php"); 
    @DeleteTrackingOld(50);
	//@CheckBkdb();
}


function ImportClass($cl)
{
    $file   = '../includes/class_'.$cl.'.php';
    if(is_file($file))
    {
        @include_once($file) ;
    }    
}

function CheckBkdb()
{
global $dbsql;
	$arrdate=array(1,11,21,30);
	$date=intval(date("d"));
	$pathfile="../db/bkdb_".date("Y-m-d").".sql";
	if(is_file($pathfile) || !in_array($date,$arrdate))return;
	@$dbsql->Backup("",$pathfile,false,false,true);
}


function DeleteTrackingOld($day=10)
{
global $dbsql;
    $date=gpc_add_date(gpc_getDateNow(),0-$day);
    $sql_delete="delete from tbltracking where dDate<'$date'";
    $dbsql->query($sql_delete);
}


function Trim_Url($url,$name='')
{
    $url=trim($url);
    if(empty($url))$url=$name;
	$url=gpc_utf8_to_ascii(trim($url));
	$url=preg_replace("([^a-zA-Z.0-9])","-",$url);
	$url=preg_replace("((-){2}|(-$))","",$url);
	$url=strtolower($url);
	return $url;
}

function trim_array(&$arr)
{
	if(!is_array($arr))return;
	array_walk($arr, 'trim_value');
	return $arr;
}

function trim_value(&$value)
{
    $value = trim($value);
}


function page_transfer($msg,$page='',$reset=false,$transfer=1)
{
global $AjaxFrame,$module,$AjaxOpt,$child;
    if($AjaxOpt==3)
    {
        gpc_setSession("Msg_Alert_Redirect",$msg);
    }
    if(strpos($page,"module=")===false)
    {
        $page="?module=$module&".$page;
    }
    if(!empty($child))
    {
        $page.='&child='.$child;
    }
    if($AjaxFrame===true)
	{
		echo ".(*_*)ok(*_*)".$msg."(*_*)".$page."(*_*)";
		if($reset==true)echo "reset(*_*)";
		exit;
	}
	if($transfer==1)
    {
        gpc_setSession("Msg_Alert_Redirect",$msg);
        header("location: ".$page);
        exit;
    }
    $showtext = $msg;
	$page_transfer = $page;
	include("templates/transfer.tpl");
	exit();
}

function error_transfer($msg,$page='',$transfer=1)
{
global $AjaxFrame,$module;
    if(strpos($page,"module=")===false)
    {
        $page="?module=$module&".$page;
    }
	if(empty($msg))return false;
	if($AjaxFrame===true)
	{
		echo ".(*_*)false(*_*)".$msg."(*_*)";
		exit;
	}
    if($transfer==1)
    {
        gpc_setSession("Msg_Alert_Redirect",$msg);
        header("location: ".$page);
        exit;
    }
	$showtext = $msg;
	$page_transfer = $page;
	include("templates/transfer.tpl");
	exit();
}


function Insert_Tag($taglink,$tags,$id,$type,$title)
{
	global $dbsql,$language,$hasTag;
	$type=trim($type);
	if(strlen($taglink)<5 || $id<=0 || empty($type) || empty($title) || $hasTag!==true)
	{
		return false;
	}
	$tagarr=preg_split("/,|-/",$tags);
	if(is_array($tagarr))
	{
		$tagarr=array_unique($tagarr);
		trim_array($tagarr);
		$tags=join(",",$tagarr);
		$tags=gpc_utf8_to_ascii($tags);
	}

	$sql_select = "SELECT iId FROM tbltag WHERE iId = '$id' AND cType like '$type'";

	$sql_update = "UPDATE tbltag SET cTag = '$tags',cTagLink = '$taglink',cTitleTag='$title'
					WHERE iId = '$id' AND cType like '$type'";

	$sql_insert = "INSERT INTO tbltag (iId, cType, cTag, cTagLink,cTitleTag,cLanguage)
					VALUES ('$id','$type','$tags','$taglink','$title','$language')";

	$rs=$dbsql->query($sql_select);
	$rows = $dbsql->num_rows($rs);
	if($rows > 0)
	{
		$dbsql->query($sql_update);
	}
	else
	{
		$dbsql->query($sql_insert);
	}
}

function Select_Tag($id,$type)
{
global $dbsql,$language,$hasTag;
	if($hasTag!==true)return;
	$sql_select = "select cTag from tbltag where iId='$id' and cType like '$type' and cLanguage='$language'";
	$rs=$dbsql->query($sql_select);
	$tag=$dbsql->fetch_array($rs);

	return $tag['cTag'];
}

function Delete_Tag($id,$type)
{
global $dbsql,$language,$hasTag;
	if($hasTag!==true)return;

	$sql_delete = "DELETE FROM tbltag where iId='$id' and cType like '$type' and cLanguage='$language'";
	$dbsql->query($sql_delete);
}

function Insert_Tracking($cAction)
{
global $dbsql;

	  $cAction="[".date("d/m/Y : h:i A ")."] ".$cAction;
	  $cIPAddress = getenv("REMOTE_ADDR");
	  $iTrackingId = intval(gpc_getSession("TrackingId"));
	  $iAccountId = getIdAdmin();


	  //select tracking co chua?
	  $sql_select= "select cAction from tbltracking where iTrackingId = $iTrackingId";
      $rs=$dbsql->query($sql_select);
	  if($result = $dbsql->fetch_array($rs))
      {
      		$NewcActions.= $result["cAction"];
      		$NewcActions.= "<br>";
			$NewcActions.= $cAction;
	  		$NewcActions=mysql_escape_string($NewcActions);
			if(strlen($NewcActions)>64000)return;
			$sql_update= "UPDATE tbltracking SET iAccountId = $iAccountId,
					cAction = '$NewcActions',
					cIPAddress = '".$cIPAddress."', dDate = '".date("Y/m/d")."'
					WHERE  iTrackingId = $iTrackingId";

      		$dbsql->query($sql_update);
      }else
	  {
		  $sql_insert = "INSERT INTO tbltracking
						(iAccountId, cAction, cIPAddress, dDate)
						VALUES
						($iAccountId,'".$cAction."','".$cIPAddress."','".date("Y/m/d")."')";

		  $dbsql->query($sql_insert);

		  $sql_select = "select max(iTrackingId) as 'maxtrackingid' from tbltracking";
		  $rs=$dbsql->query($sql_select);
		  if( $result = $dbsql->fetch_array($rs) )
		  {
				gpc_setSession("TrackingId",$result["maxtrackingid"]);
		  }
      }


}

function liststatus($select=-1)
{
	$status[0]="No";
	$status[1]="Yes";

	$options="";
	for($i=0;$i<=1;$i++)
	{
		if($select==$i)
		{
			$options.="<option value=$i selected>".$status[$i]."</option>";
		}else
		{
			$options.="<option value=$i>".$status[$i]."</option>";
		}
	}
	return $options;
}

function liststatusOrder($select=-1)
{
	$status[0]="Pending";
	$status[1]="Paid";

	$options="";
	for($i=0;$i<=1;$i++)
	{
		if($select==$i)
		{
			$options.="<option value=$i selected>".$status[$i]."</option>";
		}else
		{
			$options.="<option value=$i>".$status[$i]."</option>";
		}
	}
	return $options;
}

function liststatusService($select=-1)
{
	$status[0]="Pending";
	$status[1]="Active";
	$status[2]="Suspend";
	$status[3]="Disable";

	$options="";
	for($i=0;$i<=3;$i++)
	{
		if($select==$i)
		{
			$options.="<option value=$i selected>".$status[$i]."</option>";
		}else
		{
			$options.="<option value=$i>".$status[$i]."</option>";
		}
	}
	return $options;
}


function liststatusyesno($select="YES")
{
	$status[1]="NO";
	$status[2]="YES";

	$name[1]="NO";
	$name[2]="YES";
	$option="";
	for($i=1;$i<=2;$i++)
	{
		if($status[$i]==$select)
		{
			$option.="<option value='".$status[$i]."' selected>".$name[$i]."</option>";
		}else
		{
			$option.="<option value='".$status[$i]."' >".$name[$i]."</option>";
		}
	}
	return $option;
}

function ListGender($select)
{
	$status[1]="1";
	$status[2]="0";
	$status[3]="-1";

	$name[1]="Male";
	$name[2]="Female";
	$name[3]="Other";
	$option="";
	for($i=1;$i<=3;$i++)
	{
		if($status[$i]==$select)
		{
			$option.="<option value='".$status[$i]."' selected>".$name[$i]."</option>";
		}else
		{
			$option.="<option value='".$status[$i]."' >".$name[$i]."</option>";
		}
	}
	return $option;
}

function list_place_Menu($select)
{
	$place[0]="None";
	$place[1]="Top";
	$place[2]="Main";
	$place[3]="Left";
	$place[4]="Right";
    $place[5]="Bottom";
    $place[6]="All";

	$option="";
	for($i=0;$i<count($place);$i++)
	{
		if($i==$select)
		{
			$option.="<option value='".$i."' selected>".$place[$i]."</option>";
		}else
		{
			$option.="<option value='".$i."'>".$place[$i]."</option>";
		}
	}
	return $option;
}

function Slit_Page($count_all)
{
global $page,$posts_per_page_post,$show_page;

	if($page<1)$page=1;
	$limitpage		= array();
	$limitpage[0]	= ($page-1) * $posts_per_page_post;
	$limitpage[1]   = $posts_per_page_post;
	$num_page   	= ceil($count_all/$posts_per_page_post);
	$num_pagelist	= 20;

	if($limitpage[0]>=$count_all && $count_all>0)
	{
		$url=preg_replace("/(&page=)([0-9]*)/i","&page=".$num_page,$_SERVER['QUERY_STRING']);
		header("location: ?".$url);
		exit;
	}
	$query_str =preg_replace("/(&page=)([0-9]*)/i","",$_SERVER['QUERY_STRING']);

    $show_page = "<div class='pages'>";
    $show_page.='Display #<select onchange="location=\'?'.$query_str.'&pip=\'+this.value"> ';
    $show_page.=OptionPInPage();
    $show_page.='</select>';
	if ($num_page > 1)
	{
       $show_page.='<span class="page">';
		for ($i=1 ; $i< $num_page + 1 ; $i++)
		{
			if(($i<($page-$num_pagelist/2) || $i>($page+$num_pagelist/2)) && $i<>1 && $i<>$num_page && $num_page>30)
			{
				if($i==($page-$num_pagelist/2)-1)
				{
					$show_page.="<a class='act' href='?".$query_str."&page=".($page-1)."'>&lt;</a><a>...</a>";
				}else if($i==($page+$num_pagelist/2)+1)
				{
					$show_page.="<a>...</a><a class='act' href='?".$query_str."&page=".($page+1)."'>&gt;</a>";
				}
				continue;
			}
			if ($i==$page) $show_page .= "<a class='current'>$i</a>";
			else $show_page .="<a class='act' href='?".$query_str."&page=".$i."'>$i</a>";
		}
		$show_page.="</span>";
        $show_page.='&nbsp;&nbsp;<span>Go Page: <input class="short" style="width:40px" id="gopagein">';
        $show_page.=' <input type="button" class="b1" value="go" ';
        $show_page.=' onclick="location.href=\'?'.$query_str.'&page=\'+getId(\'gopagein\').value"> ';
	}
    if($num_page>0)
    {
	   $show_page.='<span> Total: '.$count_all.' rows</span>';
       $show_page.=" - <span>Page $page of $num_page</span>";
    }
    $show_page.='</div>';

	return $limitpage;
}

function OptionPInPage()
{
global $posts_per_page_post,$config_page_posts;
	$options="";
	for($i=1;$i<11;$i++)
	{
		$vl=$i*$config_page_posts;
		if($vl==$posts_per_page_post)
		{
			$options.="<option value='$vl' selected>".$vl."</option>";
		}else
		{
			$options.="<option value='$vl' >".$vl."</option>";
		}
	}
	return $options;
}

function BuildActions($ida,$acts)
{
global $id,$countrow;
	$url=$_SERVER['QUERY_STRING'];
	$url=preg_replace("((opt=)(.*)(&?))","",$url);
	$url=preg_replace("((id=)([0-9]*))","",$url);
	$url=preg_replace("((&catid=)([0-9]*))","",$url);
	$html='';
	if(intval($countrow)==0)$countrow=1;
	foreach($acts as $i=> $vl)
	{
		if(stripos($vl,"move")!==false)
		{
			$html.='<a style="cursor:pointer" onmouseover="PopUpMove('.$ida.',this,event)">Move</a>';
		}
		else if(stripos($vl,"photo")!==false)
		{
			$html.='<a href="?'.$url.'&opt='.$vl.'&id='.$ida.'">'._PHOTO.'</a>';
		}
		else if(stripos($vl,"edit")!==false)
		{
			$html.='<a href="?'.$url.'&opt='.$vl.'&id='.$ida.'">'._EDIT.'</a>';
		}else if(stripos($vl,"del")!==false)
		{
			$html.='<a href="#Delete" onclick="if(confirm(\''.getLang('Do you want delete').'?\'))';
			$html.='location =\'?'.$url.'&opt='.$vl.'&id='.$ida.'&catid='.$id.'\'">'._DELETE.'</a> ';
		}
		if($i<count($acts)-1)$html.=' - ';
	}
	$countrow++;
	return $html;
}

function getOrderInput($bottom=false)
{
global $act;
	$vl='<select name="TopBottomOrder" onchange="OrderChangese(this)">';
    if(strpos($act,'edit')!==false)
    {
        $vl.='<option value="-1">'.getLang('No Change').'</option>';
    }
    $vl.='<option value="1" >'.getLang('Top').'</option>';
    $vl.='<option value="2" '.(($bottom==true)? 'selected': '').'>'.getLang('Bottom').'</option>';
    $vl.='</select>';
    $vl.='<input style="width:40; display:none" maxlength="3" name="Order" id="Order" value="1">';
	return $vl;
}

function getUrlBack()
{
    global $url_Back;
    $url=gpc_getSession("UrlBack");
    if(!empty($url))
    {
        $url_Back   = $url;
    }
	return $url_Back;
}

function datePost()
{
	return date("Y-m-d H:i:s");
}

function getOrderList($i)
{
global $page,$posts_per_page_post;
	$order=($i+1)+($page-1)*$posts_per_page_post;
	return $order;
}

function GetOrderForInsert($place,$order,$idP=-1,$table='tblcategory')
{
global $dbsql,$language;

	switch(intval($place))
	{
		case 1:
			$sql_update="update $table set iOrder=iOrder+1 ";
			if($idP>0)$sql_update.=" where iParentId ='$idP'";
			if($dbsql->query($sql_update))
			{
				$order=1;
			}
			break;
		case 2:
			$sql_select="select max(iOrder) as max from $table ";
			if($idP>0)$sql_update.=" where iParentId ='$idP'";

			$rs=$dbsql->query($sql_select);

			$result=$dbsql->fetch_array($rs);
			$order=($result['max']>0)? intval($result['max']) +1 : $order;
			break;
        default:
            $order=-1;
            break;
	}

	$order=intval($order);
	return $order;
}

function Createfolderupload($url)
{
global $folder_img_upload;
	$url=Trim_Url($url);
	if(empty($url) || empty($folder_img_upload))return ;
	if(substr($folder_img_upload,strlen($folder_img_upload)-1,1)!="/")
	{
		$folder_img_upload.="/";
	}
	@mkdir("../".$folder_img_upload.$url);
}

function replace_pathlocal($text)
{
	global $folder_path_root;
	//$text = str_replace("../../",$folder_path_root,$text);
	//$text = str_replace("../",$folder_path_root,$text);
	return $text;
}

function getConfig($name,$default="",$all=false)
{
	global $dbsql,$language;

	if(isset($GLOBALS['config_'.$name]))return $GLOBALS['config_'.$name];

	$sql_select="select cValue from tblconfig where cName='$name'";
    if($all==false)
    {
        $sql_select.= " and cLanguage='$language'";
    }
	if($result=$dbsql->query_fetch($sql_select))
	{
		$value=$result['cValue'];
		$GLOBALS['config_'.$name]=$value;
	}
	return $value;
}

function saveConfig($name,$value)
{
global $dbsql,$language;

	$sql_select="select cName from tblconfig where cName='$name' and cLanguage='$language'";
	if($dbsql->query_fetch($sql_select)==false)
	{
		$sql_insert="insert into tblconfig(cName,cValue,cLanguage)
					values('$name','$value','$language')";
		if($dbsql->query($sql_insert))return true;
	}else
	{
		$sql_update="update tblconfig set cValue='$value' where cName='$name' and cLanguage='$language'";
		if($dbsql->query($sql_update,true))
		{
			return true;
		}
	}
	return false;
}

function returnCheckurl($rows,$url,$idP=0)
{
global $AjaxFrame;
	$msg="";
	$check_ok=true;
	if(empty($url))
	{
		$check_ok=false;
		$msg= "Url empty! Please enter Url";
	}
	else if($rows>0)
	{
		$check_ok=false;
		$msg= "Url is exists! Please change Url";
	}
	else if(isset($_GET['ajax']) || isset($_POST['ajax']))
	{
	    $msg= " ok ";
	}

	if(!empty($msg))
	{
		echo ".(*_*)".(($check_ok)? "ok" : "false")."(*_*)".$msg."(*_*).";
		exit;
	}
}

function CheckUrlString($url,$table="tblcategory",$idP=-2)
{
	global $dbsql,$id,$language;

    $sql_select = "select iId from $table where cUrlString = '$url' and iId!='$id' ";
    if($idP>-2)
    {
        $sql_select.=" and iParentId='$idP'";
    }
    $sql_select.=" and cLanguage='$language'";

    $rs=$dbsql->query($sql_select);
    $rows = $dbsql->num_rows($rs);
	returnCheckurl($rows,$url,$idP);
}

function IncludeFunction($module)
{
    $file="source/$module/functions.php";
    if(is_file($file))
    {
        @include_once($file);
    }
}

?>